import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react'

import { getCols } from '../common/getCols'

import { Row, Col, Button, Popover } from 'antd'
import styles from './connetTags.less'


export default forwardRef(({...params},ref) => {
    const { onChange, fcols, data } = params

    // 初始化参数
    const syscols = getCols()
    var connettags = {}
    syscols.forEach(col => {
        connettags[col.key] = []
    })

    // 初始化HOOK
    const [fls_cols, setFls_cols] = useState([])
    const [connet_tags, setConnet_tags] = useState(connettags)

    useEffect(() => {
        let divs = document.getElementsByTagName('div')
        for (const div of divs) {
            div.ondragover = (e) => {
                e.preventDefault()
            }
        }
        // if(fcols!==fls_cols) setFls_cols(fcols.filter(i => i).map(col => col.title))
    })

    useImperativeHandle(ref, () => ({
        // changeVal 就是暴露给父组件的方法
        changeVal: (newVal) => {
            console.log('ooooooooooooooooooo', newVal)
            handleReset()
        }
    }))

    // 重置所有数据
    const handleReset = () => {
        setFls_cols(fcols.filter(i => i).map(col => col.title))
        setConnet_tags(connettags)
    }

    // 拖动公共函数
    const drop = (e, m) => {
        e.preventDefault()

        const dr = () => {// 获取拖动元素参数[0]id,[1]title
            let so = e.dataTransfer.getData("Text").split("|")

            // 判断是否拖到系统标题
            if (e.target.className.search('sys') !== -1 || e.target.parentNode.className.search('sys_col') !== -1) {
                // 判断是否原位移动
                let parentNode1 = document.getElementById(so[0]).parentNode
                if (e.target.id !== parentNode1.id) {
                    // 不是原位移动则进行下面函数

                    if (e.target.className === parentNode1.className) {
                        // 从系统移动
                        // 处理目标ID获取KEY
                        let key = e.target.id.search('fls_') !== -1 ? e.target.parentNode.id : e.target.id

                        // 系统表头加入项目
                        let connet_tags_t = connet_tags
                        connet_tags_t[key].push(so[1])

                        connet_tags_t[parentNode1.id] = connet_tags_t[parentNode1.id].filter(i => i != so[1])

                        setConnet_tags({ ...connet_tags_t })

                    } else {
                        // 从文件拖入
                        // 处理目标ID获取KEY
                        let key = e.target.id.search('fls_') !== -1 ? e.target.parentNode.id : e.target.id

                        // 系统表头加入项目
                        let connet_tags_t = connet_tags
                        connet_tags_t[key].push(so[1])
                        setConnet_tags({ ...connet_tags_t })

                        // 文件表头删除项目
                        let fls_cols_t = fls_cols.filter(i => i != so[1])
                        setFls_cols(fls_cols_t)
                    }
                }
            }

            // 判断是否拖回文件表头
            if (e.target.id.search('fls_cols') !== -1 || e.target.parentNode.id.search('fls') !== -1) {
                // 判断是否原位移动
                let parentNode1 = document.getElementById(so[0]).parentNode.id
                let parentNode2 = document.getElementById(e.target.id).parentNode.id

                if (parentNode1 !== e.target.id) {
                    if (parentNode1 !== parentNode2) {
                        // 不是原位移动则进行下面函数

                        // 文件表头添加项目
                        let fls_cols_t = fls_cols
                        fls_cols_t.push(so[1])
                        setFls_cols([...fls_cols_t])

                        // 系统表头删除项目
                        let connet_tags_t = connet_tags
                        connet_tags_t[parentNode1] = connet_tags_t[parentNode1].filter(i => i != so[1])
                        setConnet_tags({ ...connet_tags_t })
                    }
                }
            }
        }
        var targe = e.target.className.search('fls_col_') !== -1 ? e.target.parentNode : e.target
        if (targe.children.length < m) dr()
    }

    // TAG组件
    const TagBox = (params) => {
        const { col, cid, data } = params
        console.log(data)
        return (
            <Popover content={`示意格式：${data !== null ? data[col] : null}`} trigger="hover">
                <div
                    id={`fls_col_${cid}`}
                    className={styles.fls_col}
                    draggable
                    onDragStart={(e) => {
                        e.dataTransfer.setData("Text", e.target.id + '|' + col)
                    }}
                    onDrag={e => {
                        e.preventDefault()
                        e.target.className = styles.fls_col_drag
                    }}
                    onDragEnd={e => {
                        e.preventDefault()
                        e.target.className = styles.fls_col
                    }}
                >
                    {col}
                </div>
            </Popover>
        )
    }

    return (
        <div>
            <div id="fls_cols" className={styles.fls_cols} onDrop={e => drop(e, 100)}>
                {fls_cols.map((col, cid) =>
                    <TagBox key={cid} col={col} cid={cid} data={data} />
                )}
                <div className={styles.button}>
                    <Button onClick={e => handleReset()} type="primary">刷新/重置</Button>
                    <Button onClick={e => onChange(connet_tags)} type="primary">保存关联</Button>
                </div>
            </div>
            <div id="sys_cols" className={styles.sys_cols}>
                <Row gutter={10}>
                    {syscols.map((col, cid) =>
                        <Col span={6} key={cid}>
                            <p>{col.title}<span>{connet_tags[col.key].length}/{col.multi}</span></p>
                            <div id={col.key} className={styles.sys_col}
                                onDrop={(e) => {
                                    drop(e, col.multi)
                                }}
                            >
                                {connet_tags[col.key].map((col, cids) =>
                                    <TagBox key={cids} col={col} cid={`${cid}_${cids}`} data={data} />
                                )}
                            </div>

                        </Col>
                    )}
                </Row>
            </div>
        </div>
    )
})